package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.*;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @Override
    @ApiOperation(value = "员工登录")
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus().equals(StatusConstant.DISABLE)) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    @ApiOperation(value = "新增员工")
    public void save(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        //属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);
        //1.判断数据库中是否存在该用户名
        //1.1 根据用户名查询数据库中的数据
        Employee emp = employeeMapper.getByUsername(employee.getUsername());
        //2.如果存在，抛出异常
        if (emp != null) {
            throw new UserAllreadyException(MessageConstant.USER_ALLREADY_FOUND);
        }
        //3.如果不存在，则保存
        //3.1 先保存必要的值
        //密码默认123456
        employee.setPassword(DigestUtils.md5DigestAsHex(MessageConstant.DEFAULT_PASSWORD.getBytes()));
        //创建时间
        employee.setCreateTime(LocalDateTime.now());
        //更新时间
        employee.setUpdateTime(LocalDateTime.now());
        //创建人
        employee.setCreateUser(BaseContext.getCurrentId());
        //更新人
        employee.setUpdateUser(BaseContext.getCurrentId());
        //状态
        employee.setStatus(StatusConstant.ENABLE);
        //保存
        employeeMapper.save(employee);
        //4.返回结果
    }

    @ApiOperation(value = "员工分页查询")
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //1.设置分页参数
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        //2.执行查询
        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);
        long total = page.getTotal();
        List<Employee> records = page.getResult();
        PageResult pageResult = new PageResult(total, records);
        //3.返回结果
        return pageResult;
    }

    @ApiOperation(value = "启用禁用员工账号")
    @Override
    public void startOrStop(Integer status, Long id) {
        //1.创建一个Employee对象
        Employee employee = new Employee();
        //2.设置状态值
        employee.setStatus(status);
        employee.setId(id);
        employeeMapper.update(employee);
    }

    @Override
    @ApiOperation(value = "根据id修改员工信息")
    public Employee getById(Long id) {
        //1.根据id查询员工数据
        Employee employee = employeeMapper.getById(id);
        //2.判断是否为空,如果为空，抛出异常
        if (employee == null) {
            throw new UserNotExistException(MessageConstant.USER_NOT_FOUND);
        }
        return employee;

    }

    @Override
    @ApiOperation(value = "修改员工信息")
    public void update(EmployeeDTO employeeDTO) {
        //1.根据id查询员工数据
        Employee employee = employeeMapper.getById(employeeDTO.getId());
        //2.判断是否为空,如果为空，抛出异常
        if (employee == null) {
            throw new UserNotExistException(MessageConstant.USER_NOT_FOUND);
        }
        //3.如果非空，则修改员工数据
        BeanUtils.copyProperties(employeeDTO, employee);
        //3.1 先修改必要的值
        employee.setUpdateTime(LocalDateTime.now());
        Long currentId = BaseContext.getCurrentId();
        System.out.println(currentId);
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);
    }

    @Override
    @ApiOperation(value = "修改密码")
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        //1.根据id查询员工数据
        Employee employee = employeeMapper.getById(BaseContext.getCurrentId());
        //2.判断是否为空,如果为空，抛出异常
        if (employee == null) {
            throw new UserNotExistException(MessageConstant.USER_NOT_FOUND);
        }
        String oldPassword = passwordEditDTO.getOldPassword();
        String newPassword = passwordEditDTO.getNewPassword();
        //3.判断旧密码是否正确
        String password = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        if (!password.equals(employee.getPassword())) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        //4.要求新密码要在6位以上
        if (newPassword.length() < 6) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_EDIT_FAILED);
        }
        employee.setPassword(DigestUtils.md5DigestAsHex(newPassword.getBytes()));
        employeeMapper.update(employee);
    }

}
